import java.util.Scanner;
import java.util.InputMismatchException;

public class Sum2DArrays2 {

    public static void main(String[] args) {
      try{
        int[][] matrix1, matrix2, matrix3;
        matrix1 = readArray( );
        matrix2 = readArray( );

        matrix3 = addMatrix(matrix1, matrix2);

        System.out.printf("%nThe sum of matrix1 and matrix2 is:%n");
        displayArray(matrix3);
      }catch(InputMismatchException | IllegalStateException | IllegalArgumentException e){
      	  System.out.println(e);
      }
    }

    private static void displayArray(int[][] x){
         // Display matrix x row-wise
        for(int r = 0; r < x.length; r++){
        	for(int c = 0; c < x[r].length; c++){
        		System.out.printf("%3d  ", x[r][c]);
        	}

        	System.out.printf("%n");
        }
    }

    private static int[][] readArray( ){
    	Scanner scanner = new Scanner(System.in);
    	System.out.printf("Enter number of rows: ");
        int numRows = scanner.nextInt();
        System.out.printf("Enter number of columns: ");
        int numColumns = scanner.nextInt();

        if(numRows <= 0 || numColumns <= 0){
        	throw new IllegalStateException("Invalid number of rows or columns");
        }

        int[][] x = new int[numRows][numColumns];
    	System.out.printf("Enter %d * %d elements of matrix row-wise:%n", numRows, numColumns);
        for(int r = 0; r < x.length; r++){
        	for(int c = 0; c < x[r].length; c++){
        		x[r][c] = scanner.nextInt();
        	}
        }

        return x;
    }

     private static int[][] addMatrix(int[][] x, int[][] y){
        if(x.length != y.length || x[0].length != y[0].length)
             throw new IllegalArgumentException("Array dimensions are not equal");
        int[][] m = new int[x.length][x[0].length];
        for(int r = 0; r < x.length; r++){
        	for(int c = 0; c < y[r].length; c++){
        		m[r][c] = x[r][c] + y[r][c];
        	}
        }
        return m;
    }
}
